<?php
/**
 * 后台订单表操作模型
 * @author lifw
 */
class MOrderLog extends MY_Model {
	protected $table = 'order_log';
	
	
	/**
	 * 订单列表查询
	 * @param array $limit 分页参数
	 * @param bool $sort 排序标志
	 */
	public function getList($limit, $sort=false){
		$this->db->select($this->table.'.*');
		$this->db->distinct();
		$this->db->from($this->table);
		if($limit){
			$this->db->limit($limit['limit'],$limit['offset']);
		}
		$this->formfilter->doFilter();
		if($sort){
			$this->db->order_by($this->table.'.id', 'asc');
		}else{
			$this->db->order_by($this->table.'.id', 'desc');
		}
		$query = $this->db->get();
		return $query->result();
	}
	
	/**
	 * 关联订单列表计数
	 * @param array $indexWhere 关联索引表的条件语句
	 */
	public function getCount(){
		$this->db->select('count(distinct '.$this->db->dbprefix($this->table).'.id) as num');
		$this->db->from($this->table);
		$this->formfilter->doFilter();
		$tmp = $this->db->get()->result();
		return (int)$tmp[0]->num;
	}
	
	public function getById($order_id){
		$this->db->select($this->table.'.*, types.name as product_type_name, site.domain, payment_method.name as payment_method_name');
		$this->db->from($this->table);
		$this->db->join('site', $this->table.'.site_id=site.id', 'left');
		$this->db->join('types', $this->table.'.product_type=types.id', 'left');
		$this->db->join('payment_method', $this->table.'.payment_method=payment_method.id', 'left');
		
		$this->db->where($this->table.'.id', $order_id);
		$query = $this->db->get();
		return $query->row();
	}
	
	/** 更新订单信息 */
	public function save($order, $log = NULL, $update_index = TRUE){
		$this->load->model('MOrderIndex');
		$this->db->trans_start();
		$success = parent::save($order);
		if($success && $update_index){
			foreach ($this->index_cols as $col){
				if(property_exists($order,$col) && strlen($order->{$col}) > 0){
					$this->MOrderIndex->save((object)array(
							'order_id'=>$order->id,
							'table_name'=>$this->table,
							'col_name'=>$col,
							'col_value'=>$order->{$col}
					));
				}
			}
		}
		if($success && $log){
			$this->load->model('MOrderLog');
			$log->order_id = $order->id;
			$log->payment_state = $order->payment_state;
			$log->delivery_state = $order->delivery_state;
			$log->state = $order->state;
			$log->risk = $order->risk;
			$log->create_time = $this->update_time = time();
			$this->MOrderLog->add($log);
		}
		return $this->db->trans_complete();
	}

}
